package FlyGame;

import org.jetbrains.annotations.NotNull;
import org.junit.Test;

import java.sql.*;


public class DbUtil {

    Connection coon;

    public DbUtil() {
        this.connection();
    }

    public void connection (){
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        String URL = "jdbc:mysql://127.0.0.1/2_com?characterEncoding=utf-8";
        String username = "1197396802";
        String password = "chy2001.10.25";
        try {
            coon = DriverManager.getConnection(URL,username,password);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    //增 insert into table_name values(?...)
    //删 delete from table_name where ?
    public int doUpdate(String sql,Object[] params){
        connection();
        try {
            PreparedStatement preparedStatement = coon.prepareStatement(sql);
            for(int i = 0 ;i<params.length;i++){
                preparedStatement.setObject(i+1,params[i]);
            }

            return preparedStatement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    //查 select * from table_name where ?
    public ResultSet doQuery(String sql,Object[] params){
        connection();
        try {
            PreparedStatement preparedStatement = coon.prepareStatement(sql);
            for(int i = 0;i<params.length;i++){
                preparedStatement.setObject(i+1,params[i]);
            }
            return preparedStatement.executeQuery();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    //打印查询结果
    public int[] paintResult(@NotNull ResultSet rs){
        int[] result = new int[5];
        int i = 0;
        try {
            while (rs.next()) {
                if(i>=5){
                    break;
                }
                result[i] = rs.getInt("score");
                i++;
            }
            return result;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return result;
    }

    public void getClose(){
        try {
            this.coon.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }


    @Test
    public void test(){
        DbUtil dbUtil = new DbUtil();
        dbUtil.connection();
//        Object[] params = {"12345","67890","哈哈"};
//        System.out.println(doUpdate("insert into student value(?,?,?)", params));

        Object[] params2 = {"12345"};
        ResultSet resultSet = dbUtil.doQuery("select * from student where username = ?", params2);
        dbUtil.paintResult(resultSet);

    }

}
